package com.market.service.impl;

import com.market.entity.Buyer;
import com.market.entity.Goods;
import com.market.entity.Store;
import com.market.mapper.StoreMapper;
import com.market.service.BuyerService;
import com.market.service.GoodsService;
import com.market.service.StoreService;
import com.market.utils.LocationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;
import java.util.Map;

@Service
public class StoreServiceImpl implements StoreService {
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private BuyerService buyerService;
    @Autowired
    private GoodsService goodsService;

    @Override
    public boolean addStore(Store store) {
        String address = store.getAddress();
        Map<String, Object> lngAndLat = LocationUtil.getLngAndLat(address);
        store.setLatitude(Double.parseDouble(String.valueOf(lngAndLat.get("latitude"))));
        store.setLongitude(Double.parseDouble(String.valueOf(lngAndLat.get("longitude"))));
        int i = storeMapper.addAStore(store);
        if (i<=0){
            return false;
        }
        return true;
    }

    @Override
    public Store findStore(int id) {
        if (storeMapper.selectStoreById(id)==null){
            return new Store();
        }
        Store store = storeMapper.selectStoreById(id);
        return store;
    }

    //小店邀请人，邀请成功后小店加 10块钱收益
    @Override
    public boolean inviteBuyer(int buyerId,int storeId) {

        return false;
    }

    //提现
    @Override
    @Transactional
    public boolean cashAdvance(int id,double money) {
        Store store = storeMapper.selectStoreById(id);
        if (store.getCurrentAccount()<money){
            try {
                throw new Exception("您的余额不足，无法提现");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        int i = storeMapper.modifyMoney(id, money);
        return i==1;
    }

    //到货后通知买家 socket
    @Override
    public boolean informBuyer(int buyerId,int goodsId) {
        return false;
    }




   // 修改小店状态
    public boolean modifyState(int id,int state){
        int i = storeMapper.modifyStoreState(id, state);
        return i==1;
    }

    //查看所有小店
    @Override
    public List<Store> findAllStore() {
        List<Store> stores = storeMapper.selectAllStore();
        return stores;
    }

    @Override
    public Store storeLogin(String accountNumber, String password) {
        Store store = storeMapper.selectStoreByAccAndPwd(accountNumber, password);
        return store;
    }


}
